package com.zzy.demo.common.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.zzy.demo.common.constant.HttpConst;
import com.zzy.demo.common.dto.CodeMsg;
import com.zzy.demo.common.dto.Result;

/**
  *   全局异常
 * @author 郭凯歌
 *
 */
@Configuration
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		
		String url = request.getRequestURI().toString();
		
		ModelAndView mv = null;
		
		if(url.endsWith(HttpConst.REQUEST_URL_SUFFIX_JSON)) {
			if(ex instanceof BizException) {
				Result<CodeMsg> result= Result.error(ex.getMessage());
				mv= new ModelAndView("jsonView",result.toMap());
			}else {
				Result<CodeMsg> result= Result.error(ex.getMessage());
				mv= new ModelAndView("jsonView",result.toMap());
			}
		}else if(url.endsWith(HttpConst.REQUEST_URL_SUFFIX_PAGE)) {
				Result<CodeMsg> result= Result.error(ex.getMessage());
				mv= new ModelAndView("exception",result.toMap());
		}else {
			Result<CodeMsg> result= Result.error(CodeMsg.SERVER_ERROR);
			mv= new ModelAndView("exception",result.toMap());
		}
		
		return mv;
	}
	
	
	
	@Bean("jsonView")
	public MappingJackson2JsonView jsonView() {
		return new MappingJackson2JsonView();
	}

}
